/**
 * Created by zhaojm on 15/4/23.
 */
game.DynamicNail = game.BaseRole.extend({
    _sprite:null,
    _world:null,
    _layer:null,
    _body:null,
    _bodyDef:null,
    _fixtureDef:null,
    _className : "Nail",
    ctor:function(p){
        this._super();

        var sprite = new cc.Sprite(res.nail_png);
        this._sprite = sprite;
        //sprite.setColor(new cc.Color(255, 216, 95));

        var contentSize = this._sprite.getContentSize();

        p.y += contentSize.height / 2;

        sprite.x = p.x ;
        sprite.y = p.y;
        //this._sprite.setAnchorPoint(cc.p(0.5, 0));


        var b2BodyDef = Box2D.Dynamics.b2BodyDef
            , b2Body = Box2D.Dynamics.b2Body
            , b2FixtureDef = Box2D.Dynamics.b2FixtureDef
            , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
            , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
            , b2Vec2 = Box2D.Common.Math.b2Vec2;

        // 物体
        var bodyDef = new b2BodyDef();
        bodyDef.type = b2Body.b2_dynamicBody;
        bodyDef.position.Set(p.x / PTM_RATIO, p.y / PTM_RATIO);
        bodyDef.userData = this;
        this._bodyDef = bodyDef;



        // 多边形
        var polygonShape = new b2PolygonShape();
        polygonShape.SetAsArray(
            [
                new b2Vec2(-0.5, -0.4),
                new b2Vec2(0.5, -0.4),
                new b2Vec2(0, 0.5)
            ],
            3
        );

        // 定义材质
        var fixtureDef = new b2FixtureDef();
        fixtureDef.shape = polygonShape;
        fixtureDef.density = 0.0;   // 密度
        fixtureDef.friction = 0.0;  // 摩擦系数
        fixtureDef.restitution = 0.0;   // 弹性
        this._fixtureDef = fixtureDef;


    },

    getCollideRect:function(){
        var pos = this._sprite.getPosition();
        var contentSize = this._sprite.getContentSize();
        return new cc.Rect(pos.x - contentSize.width / 2, pos.y - contentSize.height / 2, contentSize.width, contentSize.height);
    },




    addToLayer:function(layer, world){
        this._layer = layer;
        layer.addChild(this._sprite);
        this._world = world;

        var b2Vec2 = Box2D.Common.Math.b2Vec2;

        //var pos = this._bodyDef.position;
        //var contentSize = this._sprite.getContentSize();

        this._body = this._world.CreateBody(this._bodyDef);
        this._body.CreateFixture(this._fixtureDef);
        //this._body.ApplyImpulse(new b2Vec2(-20, 0), cc.p(pos.x, pos.y - contentSize.height / 2));

        var v = new b2Vec2(-15, 0);
        this._body.SetLinearVelocity(v);
    },

    removeFromLayer:function(){
        this._sprite.removeFromParent();
        this._world.DestroyBody(this._body);
    },


});